package com.learn.rpc.version.version6;

import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Proxy;
import java.net.Socket;

/**
 * @author wangxing
 * @version 2020/8/14 18:30 Administrator
 */
public class Stub {
    public static final Integer PORT = 8888;

    public static Object getSub(Class clazz){
        InvocationHandler h = (proxy, method, args) -> {
            Socket socket = new Socket("localhost",PORT);

            String className  = clazz.getName();
            String methodName = method.getName();
            Class[] parametersType = method.getParameterTypes();

            ObjectOutputStream objectOutputStream = new ObjectOutputStream(socket.getOutputStream());
            System.out.println();
            objectOutputStream.writeUTF(className);
            objectOutputStream.writeUTF(methodName);
            objectOutputStream.writeObject(parametersType);
            objectOutputStream.writeObject(args);
            objectOutputStream.flush();

            ObjectInputStream objectInputStream = new ObjectInputStream(socket.getInputStream());
            Object o = objectInputStream.readObject();

            objectInputStream.close();
            objectOutputStream.close();
            socket.close();

            return o;
        };
        Object o = Proxy.newProxyInstance(clazz.getClassLoader(), new Class[]{clazz}, h);
        return o;
    }
}
